package com.ycy.ss;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class Constant{
	private static Logger logger = LogManager.getLogger(Constant.class);

	public static String BASE_URL = "http://localhost:8888/";

	private static ResourceBundle accountRB;
	
	public static String TUMBLR_BUG_REQUEST_TOKEN = null;
	
	public static String TUMBLR_BUG_TOKENSECRET = null;
	
	public static String TUMBLR_BUG_ACCESSTOKEN = null;

	static {
		accountRB = ResourceBundle.getBundle("account");
		try {
			checkSyncConf();
		} catch (Exception e) {
			accountRB = null;
			logger.error("", e);
		}

	}

	// 检查同步配置是否有问题
	private static void checkSyncConf(){
		String[] syncs = accountRB.getString("sync").split(",");
		for (String sync : syncs) {
			String[] from_to = sync.split("-");
			if (from_to.length != 2) {
				throw new RuntimeException("from_to.length != 2");
			}
			String _from = from_to[0];
			String _to = from_to[1];
			if (_from.equals(_to)) {
				throw new RuntimeException("from_to[0].equals(from_to[1]");
			}
			List<String> froms = new ArrayList<String>();
			froms.add(_from);
			_checkSyncConf(syncs, froms, _to);
		}
	}

	private static void _checkSyncConf(String[] syncs, List<String> froms, String to){
		for (String sync : syncs) {
			String[] from_to = sync.split("-");
			String _from = from_to[0];
			String _to = from_to[1];
			if (!to.equals(_from)) {
				continue;
			}
			if (froms.contains(_to)) {
				throw new RuntimeException("froms.contains(_to):" + froms + "->" + _to);
			}
			froms.add(to);
			_checkSyncConf(syncs, froms, _to);
		}
	}

	public static String getAccountInfo(String key){
		return accountRB.getString(key);
	}

	public static String[] getSync(){
		return getAccountInfo("sync").split(",");
	}

	public static String[] getSyncAllFrom(){
		Set<String> res = new LinkedHashSet<String>();
		for (String sync : getSync()) {
			res.add(sync.split("-")[0]);
		}
		return res.toArray(new String[] {});
	}

	public static String[] getSyncAllManualTo(){
		Set<String> res = new LinkedHashSet<String>();
		for (String sync : getSync()) {
			String[] from_to = sync.split("-");
			if ("manual".equals(from_to[0])) {
				res.add(from_to[1]);
			}
		}
		return res.toArray(new String[] {});
	}
}
